<?php

declare(strict_types=1);

namespace App\Service;

use App\Model\SysMenu as SysMenuModel;

class SysMenu extends BaseService
{
    // 栏目列表
    public function menuList($map)
    {
        $menu_list = SysMenuModel::query()->where($map)->orderBy('sort', 'asc')->orderBy('id','asc')->get()->toArray();
        return $this->menuToTree($menu_list, 'menu_key', 'parent_key', 'children', '', 'auth');
    }

    // 添加栏目
    public function addMenu($data)
    {
        return SysMenuModel::insert($data);
    }

    // 编辑栏目
    public function editMenu($id, $data)
    {
        return SysMenuModel::query()->where('id', $id)->update($data);
    }

    // 删除栏目
    public function deleteMenu($id)
    {
        return SysMenuModel::where('id', $id)->delete();
    }

    /**
     * 把返回的数据集转换成Tree(专属于)
     * @param $list 要转换的数据集
     * @param string $pk
     * @param string $pid
     * @param string $child
     * @param int $root
     * @return array
     */
    public function menuToTree($list, $pk = 'id', $pid = 'pid', $child = 'children', $root = '',$auth = 'auth')
    {
        // 创建Tree
        $tree = array();
        if (is_array($list)) {
            // 创建基于主键的数组引用
            $refer = array();
            foreach ($list as $key => $data) {
                $refer[$data[$pk]] = &$list[$key];
            }
            foreach ($list as $key => $data) {
                // 判断是否存在parent
                $parentId =  $data[$pid];
                if ($root == $parentId) {
                    $tree[] = &$list[$key];
                } else {
                    if (isset($refer[$parentId])) {
                        $parent = &$refer[$parentId];
                        // $parent[$child][] = &$list[$key];

                        if ($list[ $key ][ 'menu_type' ] == 2) {
                            $parent[ $auth ][] =& $list[ $key ][ 'menu_key' ];
                        } else {
                            $parent[ $child ][] =& $list[ $key ];
                        }
                    }
                }
            }
        }
        return $tree;
    }
}
